import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_basic_widgets/dialog/dialog_manager.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_lifecycle_base/tab/base_tab_page_widget.dart';
import 'package:flutter_lifecycle_base/widget/status_bar_wrap.dart';
import 'package:wallet_home/model/wallet_list_model.dart';
import 'package:wallet_home/page/theme/colors.dart';
import 'package:wallet_home/tools/aes_util.dart';
import 'package:wallet_home/tools/theme_utils.dart';
import 'package:wallet_home/tools/utils.dart';
import 'package:wallet_home/widget/coins_manager.dart';
import 'package:wallet_home/widget/wallet_add_content_widget.dart';
import 'package:wallet_home/widget/wallet_list_widget.dart';
import 'package:wallet_home/widget/wallet_page_first_card_widget.dart';
import 'package:wallet_home/widget/wallet_page_second_card_widget.dart';
import 'package:wallet_home/widget/wallet_sliver_header_widget.dart';
import '../../module_config.dart';

GlobalKey<_MainPageWalletWidgetState> walletPageKey = GlobalKey();

class MainPageWalletWidget extends BaseTabPageWidget {
  final GlobalKey<ScaffoldState> walletKey;

  MainPageWalletWidget({Key key, this.walletKey}) : super(key: key);

  @override
  _MainPageWalletWidgetState createState() => _MainPageWalletWidgetState();
}

class _MainPageWalletWidgetState
    extends BaseTabPageState<MainPageWalletWidget> {
  ScrollController _scrollController = new ScrollController();
  PageController _controller;
  String title;
  bool isNeedUpdate = false;
  bool isEyeHide = false;
  String amount = "0.00";
  List<Widget> pageViewList = List();
  String walletName = "";

  Widget pageContent;

  double topPadding = 3.0;

  Color sliverAppBarColor;

  List<CoinsBean> list = [];

  @override
  void initState() {
    super.initState();
    print("initState=====>");
    title =
        "${WXLang.$t("home_total_assets", package: ModuleConfig.moduleName)}";
    walletName = SpUtil.getString("walletNameKey");
    print(
        "meme=========+>${AESUtil.decryptString(SpUtil.getString("mnemonic_list"))}=========>$walletName");
    sliverAppBarColor = Colors.black;
    _controller = PageController(keepPage: true, viewportFraction: 1.0);

    _scrollController.addListener(() {
      if (_scrollController.position.maxScrollExtent -
              _scrollController.offset <
          5) {
        title = walletName;
        topPadding = 6.0;
        isEyeHide = true;
        sliverAppBarColor = Colors.black;
        if (isNeedUpdate) {
          isNeedUpdate = false;
          setState(() {});
        }
      } else {
        topPadding = 3.0;
        isEyeHide = false;
        title =
            "${WXLang.$t("home_total_assets", package: ModuleConfig.moduleName)}";
        if (!isNeedUpdate) {
          sliverAppBarColor = Colors.black;
          isNeedUpdate = true;
          setState(() {});
        }
        if (isNeedUpdate) {
          if (_scrollController.offset -
                  _scrollController.position.minScrollExtent <
              60) {
            isNeedUpdate = false;
            sliverAppBarColor = Colors.white;
            setState(() {});
          }
        }
      }
    });

//    pageViewList.add(WalletPageFirstCardWidget(
//      walletName: walletName,
//      amount: amount,
//    ));

    CoinManager().setCoinListListener((coins) {
      print("amount=====>$amount========>$coins");
      amount = CoinManager().getTotalAssetsCNY().toString();
      list = CoinManager().getCoinList(true);
//    pageContent = WalletListWidget(list: list);
      print("amount=====>$amount========>$list");
      setState(() {});
    });

    CoinManager().getListData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // amount = CoinManager().getTotalAssetsCNY().toString();
    print("刷新一波");
    return Scaffold(
        backgroundColor: ThemeUtils.getThemeColor(
            context: context,
            brightnessColor: Colors.grey[200],
            darkColor: Colours.dark_bg_color),
        body: SafeArea(
            child: StatusBarWrap(
                child: Stack(
          children: [
            NestedScrollView(
                controller: _scrollController,
                headerSliverBuilder: (context, innerScrolled) => [
                      SliverOverlapAbsorber(
                        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                            context),
                        sliver: SliverAppBar(
                          automaticallyImplyLeading: false,
                          backgroundColor: sliverAppBarColor,
                          title: WalletSliverHeaderWidget(
                            title: title == walletName
                                ? walletName
                                : "${WXLang.$t("home_total_assets", package: ModuleConfig.moduleName)}",
                            topPadding: topPadding,
                            amount: amount,
                            isEyeHide: isEyeHide,
                            walletKey: widget.walletKey,
                          ),
                          floating: false,
                          elevation: 0.0,
                          expandedHeight: 250,
                          titleSpacing: 0.0,
                          primary: false,
                          pinned: true,
                          toolbarHeight: 80,
                          flexibleSpace: FlexibleSpaceBar(
                            background: _flexibleSpaceWidget(),
                            collapseMode: CollapseMode.parallax,
                          ),
                        ),
                      )
                    ],
                body: WalletListWidget(list: list)),
            Offstage(
                offstage: list.length > 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  color: Color(0x60000000),
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                ))
          ],
        ))) //
        );
  }

  _flexibleSpaceWidget() {
    return Stack(
      children: [
        Container(
          child: Column(
            children: [
              Container(
                height: 210,
//                color: ThemeUtils.getThemeColor(
//                    context: context,
//                    brightnessColor: Color(0xFF045ee2),
//                    darkColor: Colors.grey[900]),
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: ThemeUtils.isDark(context)
                            ? [Colors.grey[900], Colors.grey[800]]
                            : [Colours.dark_app_main, Colours.app_main])),
              ),
              Container(
                height: 40,
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: ThemeUtils.isDark(context)
                            ? [Colors.grey[900], Colors.grey[800]]
                            : [Colors.white, Colors.white])),
              ),
            ],
          ),
        ),
        Container(
            margin: EdgeInsets.only(top: 80, bottom: 10),
            child: PageView.builder(
              physics: NeverScrollableScrollPhysics(),
              controller: _controller,
              itemCount: 1,
//              itemCount: pageViewList.length,
//              itemBuilder: (context, index) => _buildPageItem(index),
              itemBuilder: (context, index) {
                return WalletPageFirstCardWidget(
                  walletName: walletName,
                  amount: amount,
                );
              },
              onPageChanged: (index) {
//                pageContent =
//                    index == 0 ? WalletListWidget() : WalletAddContentWidget();
                setState(() {});
              },
            ))
      ],
    );
  }

  @override
  int getIndex() {
    return MainWalletPageIndex;
  }

  _buildPageItem(int index) {
    print("12313212313======>$amount");
    return pageViewList[index];
  }

  void jumpToIndex(int index) {
    scrollToPosition(_scrollController);
    _controller.jumpToPage(index);
  }

  @override
  void didAppear() {
    super.didAppear();
    print("回到钱包页面");
    list = CoinManager().getCoinList(true);
    setState(() {});
  }
}
